package com.stars.easyms.mq.core.activemq;

import com.stars.easyms.mq.exception.EasyMsMQException;
import com.stars.easyms.mq.properties.EasyMsMQProperties;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;

/**
 * 基础ActiveMQ连接工厂类
 *
 * @author guoguifang
 * @date 2018-04-23 13:54
 * @since 1.0.0
 */
final class BasicActiveMQConnectionFactory {

    private static ActiveMQConnectionFactory activeMQConnectionFactory;

    static synchronized ActiveMQConnectionFactory getActiveMQConnectionFactory(ApplicationContext applicationContext, EasyMsMQProperties easyMsMQProperties) {
        if (activeMQConnectionFactory == null) {
            String brokerUrl = easyMsMQProperties.getActivemq().getBrokerUrl();
            if (StringUtils.isNotBlank(brokerUrl)) {
                activeMQConnectionFactory = new ActiveMQConnectionFactory(easyMsMQProperties.getActivemq().getUser(), easyMsMQProperties.getActivemq().getPassword(), brokerUrl);
            } else {
                activeMQConnectionFactory = applicationContext.getBean(ActiveMQConnectionFactory.class);
                if (StringUtils.isBlank(activeMQConnectionFactory.getBrokerURL())) {
                    throw new EasyMsMQException("Please config [{}.activemq.broker-url] or [spring.activemq.broker-url] in the properties or yaml file!", EasyMsMQProperties.PREFIX);
                }
            }
        }
        return activeMQConnectionFactory;
    }

    private BasicActiveMQConnectionFactory() {
    }
}
